package service

import (
	"context"
	"fmt"
	"iris-wms/apps/admin/web/dto/din"
	"iris-wms/apps/admin/web/dto/dout"
	"iris-wms/common/model"
	"iris-wms/common/pkg/db"
	"iris-wms/common/pkg/db/dao"

	"gorm.io/gen"
	"gorm.io/gorm"
)

var _ WmsSupplierService = (*wmsSupplierService)(nil)

type WmsSupplierService interface {
	Create(model.WmsSupplier) error
	Update(model.WmsSupplier) error
	DeleteByIdList([]uint) error
	GetTable(din.WmsSupplierTableIn) ([]*dout.WmsSupplierOut, int64, error)
	GetList() ([]*dout.WmsSupplierOut, error)
}

func NewWmsSupplierService() *wmsSupplierService {
	return &wmsSupplierService{}
}

type wmsSupplierService struct{}

func (impl *wmsSupplierService) Create(in model.WmsSupplier) (err error) {
	err = db.GDB1.Create(&in).Error
	return
}

func (impl *wmsSupplierService) Update(in model.WmsSupplier) (err error) {
	err = db.GDB1.Save(&in).Error
	return
}

func (impl *wmsSupplierService) DeleteByIdList(idList []uint) (err error) {
	err = db.GDB1.Transaction(func(tx *gorm.DB) error {
		if err = tx.Delete(&model.WmsSupplier{}, "id in ?", idList).Error; err != nil {
			return err
		}
		return nil
	})
	return
}

func (impl *wmsSupplierService) GetTable(in din.WmsSupplierTableIn) (rows []*dout.WmsSupplierOut, total int64, err error) {
	q := dao.Use(db.GDB1).WmsSupplierOut
	do := q.WithContext(context.Background())

	condList := make([]gen.Condition, 0)
	if in.Enable > 0 {
		condList = append(condList, q.Enable.Eq(in.Enable))
	}
	if in.Word != "" {
		word := fmt.Sprintf("%%%s%%", in.Word)
		do = do.
			Where(do.Where(q.Code.Like(word)).
				Or(q.Name.Like(word)).
				Or(q.Phone.Like(word)))
	}
	rows, total, err = do.Where(condList...).
		Preload(q.Creator).FindByPage(in.Offset(), in.PageSize)
	return
}

func (impl *wmsSupplierService) GetList() (rows []*dout.WmsSupplierOut, err error) {
	q := dao.Use(db.GDB1).WmsSupplierOut
	do := q.WithContext(context.Background())
	rows, err = do.Find()
	return
}
